package com.whc.address.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.whc.address.domain.dto.AddressDto;
import com.whc.common.context.BaseContext;
import com.whc.address.domain.entity.Address;
import com.whc.address.mapper.AddressMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;


@Service
public class AddressServiceImpl {
    @Autowired
    private AddressMapper addressMapper;

    //添加地址
    public void addAddress(AddressDto addressDto){
        Address address = new Address();
        BeanUtils.copyProperties(addressDto,address);
        address.setUserId(BaseContext.getCurrentId());
        address.setCreateTime(LocalDateTime.now());
        address.setUpdateTime(LocalDateTime.now());
        addressMapper.insert(address);
    }
    //修改地址
    public void updateAddress(AddressDto addressDto){
        Address address = addressMapper.selectById(addressDto.getId());
        if(address==null){
            throw new RuntimeException();
        }
        address.setAddress(addressDto.getAddress());
        address.setPhoneNumber(addressDto.getPhoneNumber());
        address.setUsername(addressDto.getUsername());
        address.setIsDefault(addressDto.getIsDefault());
        address.setUpdateTime(LocalDateTime.now());
        addressMapper.updateById(address);
    }
    //删除地址
    public Long deleteAddress(Long id){
        return (long)addressMapper.deleteById(id);
    }
    //查询用户地址
    public List<Address> selectAddress(Long userId){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id",userId);
        List<Address> res = addressMapper.selectList(queryWrapper);
        return res;
    }


    public Address selectAddressById(Long id) {
        return addressMapper.selectById(id);
    }
}
